package b3.widget.basic
{
	import flash.display.*;
	import flash.events.*;
	import flash.utils.*;
	
	public class AutoScrollPane extends BasicWidget
	{
		private var container:Sprite;
		private var windowWidth:Number;
		private var windowMask:Sprite;
		private var timer:Timer;
		
		public function AutoScrollPane(width:Number)
		{
			super();
			container = new Sprite();
			windowMask = new Sprite();
			container.mask = windowMask;
			windowWidth = width;
			this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			this.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
		}
		
		private function onAddedToStage(event:Event):void
		{
			windowMask.graphics.beginFill(0x000000);
			windowMask.graphics.drawRect(0, 0, windowWidth, container.height);
			windowMask.graphics.endFill();
			addChild(container);
			addChild(windowMask);
			if (windowWidth < container.width)
			{
				timer = new Timer(100);
				timer.addEventListener(TimerEvent.TIMER, onTick);
				timer.start();
			}
		}

		private function onRemovedFromStage(event:Event):void
		{
			if (timer != null)
			{
				timer.removeEventListener(TimerEvent.TIMER, onTick);
				timer.stop();
			}
			timer = null;
		}
		
		private function onTick(event:Event):void
		{
			if (container.x < -container.width)
				container.x = windowWidth;
			else
				container.x -= 2;
		}
		
		public function addItem(item:DisplayObject):void
		{
			item.x = container.width > 0 ? container.width + 150 : 0;
			container.addChild(item);
		}
		
	}
}